﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 手写IOC.Container
{
    public class MarsContainer : IMarsContainer
    {
        //字典表存储Ioc的构建信息
        private Dictionary<string, Type> pairs = new Dictionary<string, Type>();

        public void Register<TFrom, TOut>() where TOut : TFrom
        {
            pairs.Add(typeof(TFrom).FullName, typeof(TOut));
        }

        public TFrom Resolve<TFrom>()
        {

            return (TFrom)ResolveObject(typeof(TFrom));
        }
        /// <summary>
        /// 递归
        /// </summary>
        /// <param name="abstractType"></param>
        /// <returns></returns>
       private object ResolveObject(Type abstractType)
        {
            string key = abstractType.FullName;
            Type type = pairs[key];
            #region 准备构造函数的参数
            //获取构造函数集合
            var ctorList = type.GetConstructors();

            List<object> paraList = new List<object>();     //构造函数集合
            foreach (var ctor in ctorList)
            {
                foreach (var item in ctor.GetParameters())
                {
                    //获取参数类型
                    Type paraType = item.ParameterType;
                    var paraInstance = ResolveObject(paraType);
                    if (paraInstance != null)
                    {
                        paraList.Add(paraInstance);
                    }
                }
            }
          
            #endregion
            object tOut = Activator.CreateInstance(type, paraList.ToArray());
            return tOut;
        }
    }
}
